package admin

import (
	"github.com/gin-gonic/gin"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
	"strconv"
)

type MemberJson struct {
	ID              int     `json:"id"`
	Pid             int     `json:"pid"`             //上级ID
	PName           string  `json:"p_name"`          //上级
	Levelid         int     `json:"levelid"`         //会员等级ID
	LevelName       string  `json:"level_name"`      //
	Money           float64 `json:"money"`           //余额
	Totalcommission float64 `json:"totalcommission"` //总计获得的佣金
	Commission      float64 `json:"commission"`      //佣金余额
	Score           int     `json:"score"`           //积分
	Nickname        string  `json:"nickname"`        //昵称
	Headimg         string  `json:"headimg"`         //头像
	Sex             string  `json:"sex"`             //性别
	Realname        string  `json:"realname"`        //姓名
	Tel             string  `json:"tel"`             //手机号
	Usercard        string  `json:"usercard"`        //身份证号
	Country         string  `json:"country"`         //国家
	Province        string  `json:"province"`        //省份
	City            string  `json:"city"`            //城市
	Area            string  `json:"area"`            //区域
	Address         string  `json:"address"`         //地址
	Birthday        string  `json:"birthday"`        //生日
	Createtime      int     `json:"createtime"`      //创建时间
	LastVisittime   int     `json:"last_visittime"`  //上次访问时间
	Platform        string  `json:"platform"`        //来源平台 mp公众号 wx小程序
}
type MemberJsonData struct {
	ID       int    `json:"id"`
	Aid      int    `json:"aid"`
	Nickname string `json:"nickname"`
	Levelid  int    `json:"levelid"` //会员等级ID
	Pid      int    `json:"pid"`     //上级ID
	Page     int    `json:"page"`
	Limit    int    `json:"limit"`
}

// 获取会员列表
func MemberList(c *gin.Context) {
	//接收
	var jsonData MemberJsonData
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var list []MemberJson
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	selectData := "m_member.id,m_member.pid,c.nickname as p_name,m_member.levelid,m_member_level.name as level_name,m_member.money,m_member.totalcommission,m_member.commission" +
		",m_member.score,m_member.nickname,m_member.headimg,m_member.sex,m_member.realname,m_member.tel,m_member.usercard,m_member.country,m_member.province" +
		",m_member.city,m_member.area,m_member.address,m_member.birthday,m_member.createtime,m_member.last_visittime,m_member.platform"
	tx := models.DB.Table("m_member").Select(selectData).Joins("left join m_member_level on m_member_level.id=m_member.levelid").Joins("left join m_member c on c.id=m_member.pid")
	if jsonData.ID > 0 {
		tx = tx.Where("m_member.id=?", jsonData.ID)
	}
	if jsonData.Aid > 0 {
		tx = tx.Where("m_member.aid=?", jsonData.Aid)
	}
	if jsonData.Levelid > 0 {
		tx = tx.Where("m_member.levelid=?", jsonData.Levelid)
	}
	if jsonData.Nickname != "" {
		tx = tx.Where("m_member.nickname LIKE ?", jsonData.Nickname)
	}
	if jsonData.Pid > 0 {
		tx = tx.Where("m_member.pid=?", jsonData.Pid)
	}
	tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("id desc").Find(&list)
	if tx.Error != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10001,
			"msg":  tx.Error,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}

// 修改会员信息
func MemberEdit(c *gin.Context) {
	//获取传值
	var jsonData models.MMember
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	//修改数据
	var editData = map[string]interface{}{
		"nickname": jsonData.Nickname,
		"headimg":  jsonData.Headimg,
		"sex":      jsonData.Sex,
		"realname": jsonData.Realname,
		"tel":      jsonData.Tel,
		"usercard": jsonData.Usercard,
		"birthday": jsonData.Birthday,
		"levelid":  jsonData.Levelid,
		"pid":      jsonData.Pid,
	}
	if jsonData.Pwd != "" {
		//生成MD5密码
		myPassword := define.GetMD5(jsonData.Pwd)
		editData["pwd"] = myPassword
	}

	err = models.DB.Model(new(models.MMember)).Where("id=?", jsonData.ID).Updates(&editData).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10003,
			"msg":  err.Error(),
		})
		return
	}
	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，修改了会员信息:" + strconv.Itoa(jsonData.ID) + "的内容"
	models.LogAdd(3, "修改会员信息", userId, logData, bid, jsonData.Aid)

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 删除会员
func MemberDel(c *gin.Context) {
	var jsonData models.MMember
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var data models.MMember
	models.DB.Model(new(models.MMember)).Where("id=?", jsonData.ID).First(&data)
	tx := models.DB.Begin()

	//删除
	err = tx.Delete(&models.MMember{}, jsonData.ID).Error

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10004,
			"msg":  err.Error(),
		})
		tx.Rollback()
		return
	}
	tx.Commit()

	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，删除了一个会员:" + data.Nickname
	models.LogAdd(4, "删除会员", userId, logData, bid, jsonData.Aid)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}
